﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Text;

using log4net;
using log4net.Config;
using System.Reflection;

namespace AutoRule
{
    class CExpWarOffsetWorker
    {
        public void Start()
        {
            _worker.Start();
        }

        public void Stop()
        {
            _WorkerStopEvent.Set();
            _worker.Join();
         }

        public static void dowork()
        {
            while (true)
            {
                GetVal();
                doCheck();

                if(_WorkerStopEvent.WaitOne(10 * 1000, true))
                    return;
            }
            
        }

        private static void GetVal()
        {
            List<COffRule> RuleList = COffsetRules.GetInstance().Get();
            if (RuleList.Count < 1)
            {
                ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                log.Warn("工艺参数预警-差值监测，规则数量少于1条，退出监测");
                return;
            }
            String Url = "http://" + CConfig.GetInstance()._OpcSvrIp + ":" + CConfig.GetInstance()._OpcSvrPort + "/Data";
            String request = "action=getvars&";
            foreach (COffRule it in RuleList)
            {
                request += it.varid + "|";
            }
            request = request.Substring(0, request.Length-1);
            CHttpClient client = new CHttpClient();
            String reponse = client.HttpPost(Url, request);
            String[] sReq = reponse.Split('&');
            if (sReq.Length == 2)
            {
                String[] vars = sReq[1].Split(',');
                foreach (String it in vars)
                {
                    String[] values = it.Split('=');
                    foreach (COffRule itRule in RuleList)
                    {
                        if (values[1].Equals("null"))
                        {
                            ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                            log.Error("id:" + values[0] + " value: null");
                            continue;
                        }
                        if (itRule.varid == int.Parse(values[0]))
                        {
                            itRule.varvalue = Convert.ToDouble(values[1]);
                            break;
                        }
                    }
                }
            }

            COffsetRules.GetInstance().Set(ref RuleList);
        }

        private static void doCheck()
        {
            List<COffRule> RuleList = COffsetRules.GetInstance().Get();
            if (RuleList.Count < 1)
            {
                ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                log.Warn("工艺参数预警-差值监测，规则数量少于1条，退出监测");
                return;
            }
            _avg.reset();
            foreach (COffRule itRule in RuleList)
            {
                _avg.sum(itRule.DevType, itRule.varvalue);
            }

            _avg.doavg();
            foreach (COffRule itRule in RuleList)
            {
                double avg = _avg.getavg(itRule.DevType);
                if (System.Math.Abs(itRule.varvalue - avg) >= itRule.offsetvalue)
                {
                    ++itRule.occurtimes;
                    ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                    log.Warn("工艺参数-偏值预警：" + itRule.DevName + " 连续监测到" + itRule.occurtimes + "次预警");
                    if (itRule.occurtimes >= 3)
                    {
                        CDB.GetInstance().InsertExpWarRep(itRule.ruleid, itRule.DevName, itRule.DevType, avg, itRule.offsetvalue, 0, 0, itRule.varvalue, 0, 1, itRule.VarName);
                        itRule.occurtimes = 0;
                    }
                }
                else
                {
                    ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                    log.Warn("工艺参数-偏值预警：" + itRule.DevName + " 复位");
                    itRule.occurtimes = 0;
                }

            }

        }



       private static ManualResetEvent _WorkerStopEvent = new ManualResetEvent(false);
       private Thread _worker = new Thread(new ThreadStart(dowork));
       private static CAvg _avg = new CAvg();
    }

 



}
